package com.mms.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RequestUtils {
    public static final String PARAM_SEP = ",";

    public static String getURI(HttpServletRequest request) throws IllegalStateException {
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        int start = uri.indexOf(contextPath);
        return uri.substring(start + contextPath.length());
    }

    public static String getString(HttpServletRequest request, String name, String defaultValue) {
        String[] values = request.getParameterValues(name);
        if ((values == null) || (values.length == 0))
            return defaultValue;

        return StringUtils.join(values, ",");
    }

    public static Integer getInt(HttpServletRequest request, String name, Integer defaultValue) {
        String temp = request.getParameter(name);
        if (StringUtils.isEmpty(temp))
            return defaultValue;
        try {
            return Integer.valueOf(temp);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Integer[] getIntAll(HttpServletRequest request, String name) {
        String[] arrayOfString1;
        String[] temps = request.getParameterValues(name);
        if (temps == null)
            return new Integer[0];

        List result = new ArrayList();
        int j = (arrayOfString1 = temps).length;
        for (int i = 0; i < j; ) {
            String temp = arrayOfString1[i];
            try {
                result.add(Integer.valueOf(temp));
            } catch (Exception localException) {
            }
            ++i;
        }

        return ((Integer[]) result.toArray(new Integer[0]));
    }

    public static Double getDouble(HttpServletRequest request, String name, Double defaultValue) {
        String temp = request.getParameter(name);
        if (StringUtils.isEmpty(temp))
            return defaultValue;
        try {
            return Double.valueOf(temp);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Double[] getDoubleAll(HttpServletRequest request, String name) {
        String[] arrayOfString1;
        String[] temps = request.getParameterValues(name);
        if (temps == null)
            return new Double[0];

        List result = new ArrayList();
        int j = (arrayOfString1 = temps).length;
        for (int i = 0; i < j; ) {
            String temp = arrayOfString1[i];
            try {
                result.add(Double.valueOf(temp));
            } catch (Exception localException) {
            }
            ++i;
        }

        return ((Double[]) result.toArray(new Double[0]));
    }

    public static BigDecimal getBigDecimal(HttpServletRequest request, String name, BigDecimal defaultValue) {
        String temp = request.getParameter(name);
        if (StringUtils.isEmpty(temp))
            return defaultValue;
        try {
            return new BigDecimal(temp);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static BigDecimal[] getBigDecimalAll(HttpServletRequest request, String name) {
        String[] arrayOfString1;
        String[] temps = request.getParameterValues(name);
        if (temps == null)
            return new BigDecimal[0];

        List result = new ArrayList();
        int j = (arrayOfString1 = temps).length;
        for (int i = 0; i < j; ) {
            String temp = arrayOfString1[i];
            try {
                result.add(new BigDecimal(temp));
            } catch (Exception localException) {
            }
            ++i;
        }

        return ((BigDecimal[]) result.toArray(new BigDecimal[0]));
    }

    public static String getQueryParam(HttpServletRequest request, String name) {
        if (StringUtils.isBlank(name))
            return null;

        return StringUtils.join(request.getParameterValues(name), ",");
    }

    public static Map<String, Object> getQueryParams(HttpServletRequest request) {
        Map map = request.getParameterMap();
        Map params = new HashMap(map.size());
        for (Iterator localIterator = map.entrySet().iterator(); localIterator.hasNext(); ) {
            Entry entry = (Entry) localIterator.next();
            int len = ((String[]) entry.getValue()).length;
            if (len == 1) {
                params.put((String) entry.getKey(), ((String[]) entry.getValue())[0]);
                break;
            }
            if (len <= 1) break;
            params.put((String) entry.getKey(), entry.getValue());
        }
        return params;
    }

    public static Map<String, String> parseQueryString(String s) {
        if (s == null) {
            return Collections.EMPTY_MAP;
        }
        Map ht = new HashMap();
        StringTokenizer st = new StringTokenizer(s, "&");
        while (st.hasMoreTokens()) {
            String pair = st.nextToken();
            int pos = pair.indexOf(61);
            if (pos == -1)  continue;

            String key = pair.substring(0, pos);
            String val = pair.substring(pos + 1, pair.length());
            if (ht.containsKey(key)) {
                String oldVals = (String) ht.get(key);
                ht.put(key, oldVals + "," + val);
            } else {
                ht.put(key, val);
            }
        }
        return ht;
    }

    public static Map<String, Object> getRequestMap(HttpServletRequest request, String suffix) {
        Map data = new HashMap();
        try {
            Map map = request.getParameterMap();
            for (Iterator localIterator = map.entrySet().iterator(); localIterator.hasNext(); ) {
                Entry entry = (Entry) localIterator.next();
                String key = (String) entry.getKey();
                if (!(key.endsWith(suffix))) break;
                String tmpkey = StringUtils.substringBeforeLast(key, suffix);
                String[] value = (String[]) entry.getValue();
                if (tmpkey.indexOf(".") > -1) {
                    String[] keyArray = tmpkey.split("\\.");
                    for (int vi = 0; vi < value.length; ++vi) {
                        Map[] maps = new Map[keyArray.length];
                        for (int i = 1; i < keyArray.length; ++i) {
                            maps[i] = new HashMap();
                            if (i == keyArray.length - 1)
                                maps[i].put(keyArray[i], StringUtils.join(value, ","));
                        }

                        for (int i = 1; i < keyArray.length - 1; ++i)
                            maps[i].put(keyArray[i], maps[(i + 1)]);

                        Matcher matcher = Pattern.compile("([a-zA-Z]+)\\[([\\d]+)\\]").matcher(keyArray[0]);
                        if (matcher.find()) {
                            String resultKey = matcher.group(1);
                            int index = Integer.parseInt(matcher.group(2));
                            Vector list = (Vector) data.get(resultKey);
                            if (list == null) {
                                list = new Vector();
                                list.setSize(index + 1);
                                list.set(index, maps[1]);
                                data.put(resultKey, list);
                            } else if (list.size() < index + 1) {
                                list.setSize(index + 1);
                                list.set(index, maps[1]);
                            } else {
                                Map tmp = (Map) list.get(index);
                                if (tmp == null)
                                    list.set(index, maps[1]);
                                else
                                    tmp.putAll(maps[1]);
                            }
                        } else {
                            Map tmp = (Map) data.get(keyArray[0]);
                            if (tmp == null)
                                data.put(keyArray[0], maps[1]);
                            else
                                tmp.putAll(maps[1]);
                        }
                    }

                    break;
                }
                data.put(tmpkey, StringUtils.join(value, ","));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    public static Map<String, Object> getRequestMap(HttpServletRequest request, ParameterWrapper wrapper) {
        return wrapper.wrap(request);
    }

    public static Map<String, String> getRequestMap(HttpServletRequest request) {
        Map map = new HashMap();
        Enumeration names = request.getParameterNames();

        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            map.put(name, StringUtils.join(
                    request.getParameterValues(name), ","));
        }
        return map;
    }

    public static void setAttributes(HttpServletRequest request, Map<String, String> map) {
        for (Iterator localIterator = map.entrySet().iterator(); localIterator.hasNext(); ) {
            Entry entry = (Entry) localIterator.next();
            request.setAttribute((String) entry.getKey(), entry.getValue());
        }
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if ((!(StringUtils.isBlank(ip))) && (!("unknown".equalsIgnoreCase(ip))))
            return ip;

        ip = request.getHeader("X-Forwarded-For");
        if ((!(StringUtils.isBlank(ip))) && (!("unknown".equalsIgnoreCase(ip)))) {
            int index = ip.indexOf(44);
            if (index != -1)
                return ip.substring(0, index);

            return ip;
        }
        return request.getRemoteAddr();
    }

    public static String getQueryString(HttpServletRequest request, String[] exclude) {
        StringBuffer sb = new StringBuffer();
        List excludeList = Arrays.asList(exclude);
        Enumeration names = request.getParameterNames();

        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = StringUtils.join(request.getParameterValues(name));
            if (!(excludeList.contains(name)))
                sb.append("&").append(name).append("=").append(value);
        }

        if (sb.length() > 0)
            sb.deleteCharAt(0);
        return sb.toString();
    }

    public static String getQueryString(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        Enumeration names = request.getParameterNames();

        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = StringUtils.join(request.getParameterValues(name));
        }

        if (sb.length() > 0)
            sb.deleteCharAt(0);
        return sb.toString();
    }

    public static abstract interface ParameterWrapper {
        public abstract Map<String, Object> wrap(HttpServletRequest paramHttpServletRequest);
    }
}
